<?php
abstract class Model extends item{
    public $tableName;
    public $db;


    public function __construct(){
        $this->tableName = strtolower(get_class($this));
        $this->db = Basic::app()->createDb();
    }

    public function getTableName(){
        return $this->tableName;
    }

    abstract static function getAttributes();



    /**
     * 获取一条数据
     * @param unknown_type $where
     * @param unknown_type $order
     * @param unknown_type $offset
     * @param unknown_type $limit
     */
    public function find($where=array(), $order=null){
        $sql = $this->_buildFindQuery($where, $order, 0, 1);
        return $this->db->fetch($sql);
    }

    /**
     * 获取所有记录
     * @param unknown_type $where
     * @param unknown_type $order
     * @param unknown_type $offset
     * @param unknown_type $limit
     */
    public function findAll($where=array(), $order=null, $offset=0, $limit=0){
        $sql = $this->_buildFindQuery($where, $order, $offset, $limit);
        return $this->db->fetchAll($sql);
    }

    public function insert($data){
    	$attributes = call_user_func($this->getTableName().'::getAttributes');
    	foreach($data as $k=>$v){
			if(!in_array($k,$attributes))
				unset($data[$k]);
    	}
        return $this->db->insert($this->tableName, $data);
    }

    public function update($data,$where){
        return $this->db->update($this->tableName, $data, $where);
    }

    /**
     * 构建SQL语句
     * @param unknown_type $where
     * @param unknown_type $order
     * @param unknown_type $offset
     * @param unknown_type $limit
     */
    protected function _buildFindQuery($where, $order, $offset, $limit){
        if(count($where)==0){
            $condition = null;
        }else{
            $_array = array();
            foreach($where as $k=>$v){
            	if($k == 'in'){
            		foreach($v as $_k => $_v){
            			$_array[]  = "{$_k} in ({$_v})";
            		}
            	}else{
                	$_array[]  = "$k='{$v}'";
            	}
            }
            $condition = implode(' and ',$_array);
        }

        $sql = "select * from {$this->tableName}";
        if($condition != null){
            $sql .= ' where '.$condition;
        }
        if($order!=null){
            $sql .= ' order by '.$order;
        }
        if($offset !=0 && $limit !=0){
            $sql .= " limit {$offset},{$limit}";
        }
        return $sql;
    }



}
